<template>
  <div id="map" />
</template>

<script>
export default {
  name: 'BaiduMap',
  props: {
    mapParams: {
      type: Object,
      default: null
    },
    searchKeyword: {
      type: String,
      default: ''
    },
    isDraw: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      searchResults: []
    }
  },
  watch: {
    mapParams: {
      deep: true,
      handler() {
        const point = new BMap.Point(this.mapParams.longitude, this.mapParams.latitude) // 设置地图中心点坐标
        this.map.centerAndZoom(point, 10) // 初始化地图，设置中心点坐标和缩放级别
        // 判断是否有作业区域
        if (this.mapParams.polygon) {
          // 设置遮罩坐标
          const coordinates = this.mapParams.polygon.map(v => ({ lat: v.latitude, lng: v.longitude }))
          // 绘制遮罩多边形
          this.polygon = new BMap.Polygon(
            coordinates.map(coord => new BMap.Point(coord.lng, coord.lat)),
            { fillColor: 'rgba(242, 200, 170)', fillOpacity: 0.5, strokeWeight: 2 }
          )
          // 将遮罩添加到地图上
          this.map.addOverlay(this.polygon)
          // 自适应缩放地图，使整个遮罩可见
          this.map.setViewport(this.polygon.getPath())
        }
      }
    },
    isDraw() {
      if (!this.isDraw) {
        this.polygon.enableEditing() // 启用遮罩的编辑模式
      } else {
        this.polygon.disableEditing()
      }
    },
    searchKeyword() {
      // console.log(this.searchKeyword)
      if (this.searchKeyword.trim() !== '') {
        const localSearch = new BMap.LocalSearch(this.map, {
          onSearchComplete: (results) => {
            if (localSearch.getStatus() === BMAP_STATUS_SUCCESS) {
              this.searchResults = results.getPoi(0, 1) // 获取搜索结果的前 5 条数据
              console.log(this.searchResults)
              this.map.setCenter(new BMap.Point(this.searchResults.point.lng, this.searchResults.point.lat))
            }
          }
        })
        localSearch.search(this.searchKeyword)
      } else {
        this.searchResults = [] // 清空搜索结果
      }
    }
  },
  mounted() {
    this.map = new BMap.Map('map') // 创建地图实例
    // const point = new BMap.Point(116.404, 39.915) // 设置地图中心点坐标
    // map.centerAndZoom(point, 15) // 初始化地图，设置中心点坐标和缩放级别
    this.map.enableScrollWheelZoom(true) // 启用滚轮缩放功能
  },
  created() {
  }
}
</script>

  <style scoped>
  #map {
    z-index: 9999999999999999999999;
    height: 640px;
  }

  </style>
